package com.ch3cooh.proxy.core.impl;

import com.ch3cooh.proxy.core.BaseProxy;
import com.ch3cooh.proxy.pojo.ClassInfo;
import com.ch3cooh.rpc.annotation.HttpRpc;
import com.ch3cooh.rpc.controller.RpcService;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @功能:
 * @作者:chanson
 * @时间:2018/5/26 19:05
 */
public class JdkProxy extends BaseProxy implements InvocationHandler{

    @Override
    public Object createProxy(Class<?> target) {
        this.target = target;
        return java.lang.reflect.Proxy.newProxyInstance(target.getClassLoader(), new Class[] {target}, this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if("toString".equals( method.getName() )){
            return this.target.toString();
        }
        if("equals".equals( method.getName() )){
            Object arg = args[0];
            return this.target.equals(arg);
        }
        HttpRpc annotation = this.target.getAnnotation(HttpRpc.class);
        if(annotation!=null) {
            ClassInfo classInfo = ClassInfo.create(this.target, method, args, annotation.serviceName());
            System.out.println("调用的方法名: " + method.getName() + " ,参数: "+ Arrays.toString(args));
            Object result = RpcService.rpc(classInfo , method.getReturnType() );
            return result;
        }
        return null;
    }
}
